package com.daisuxia.web.common.Certification;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daisuxia.web.common.reslult.JsonResult;
import com.daisuxia.web.dao.IFaceRecognitionDao;
import com.daisuxia.web.pojo.FaceRecognition;
import com.daisuxia.web.service.IFaceFecogntionService;
import com.daisuxia.web.util.FaceConfig;
import com.daisuxia.web.util.HttpUtil;
import com.daisuxia.web.util.JSONUtil;
/**
 * 相关认证服务类
 * @author user
 *
 */
@Service
public class HttpCertification implements  IHttpCertification{
	@Autowired
	private IFaceFecogntionService faceFecogntionService;
	Logger logger = Logger.getLogger(getClass());
	@Override
	public JsonResult bankCard(Map<String, String> params) {
		JsonResult result=new JsonResult("0","成功");
		return result;
	}
	/**
	 * 人脸识别
	 * @param params
	 * @return
	 */
	public JsonResult face(Map<String, String> map){
		JsonResult resultCode=new JsonResult("-1","失败");
		if(StringUtils.isNotBlank(map.get("userId"))){
			Map<String, String> textMap = new HashMap<String, String>();
			//可以设置多个input的name，value
			textMap.put("api_key", FaceConfig.FACE_API_KEY);
			textMap.put("api_secret", FaceConfig.FACE_API_SECRET);
			// 确定本次比对为“有源比对”或“无源比对”。取值只为“1”或“0”
			textMap.put("comparison_type", "1");
			// 确定待比对图片的类型。取值只为“meglive”、“facetoken”、“raw_image”三者之一
			textMap.put("face_image_type", "raw_image");
			textMap.put("idcard_name",map.get("idcard_name"));
			textMap.put("idcard_number", map.get("idcard_number"));
			Map<String, String> fileMap = new HashMap<String, String>();
			String filePath =map.get("faceImageAttach");//人脸图片地址
			fileMap.put("image", filePath.replaceAll("\\\\", "\\/"));
//			logger.info("人脸识别参数params"+textMap.toString()+"图片地址："+fileMap.toString());
			String ret = HttpUtil.formUploadImage(FaceConfig.FACE_API_FACE_URL + "/faceid/v2/verify", textMap, fileMap, "");
//			System.err.print("interface" + FaceConfig.FACE_API_FACE_URL + "/faceid/v2/verify return info :" + ret);
			if(StringUtils.isNotBlank(ret)) {
				Map<String, Object> result = JSONUtil.parseJSON2Map(ret);
				if (!result.containsKey("error_message")) {
					// 有源比对时，数据源人脸照片与待验证人脸照的比对结果
					Map<String, Object> resultFaceid = (Map<String, Object>) result.get("result_faceid");
					// 	人脸比对接口的返回的误识几率参考值
					//	“1e-3”：误识率为千分之一的置信度阈值；
					//	“1e-4”：误识率为万分之一的置信度阈值；
					//	“1e-5”：误识率为十万分之一的置信度阈值;
					//	“1e-6”：误识率为百万分之一的置信度阈值。
					Map<String, Object> thresholds = (Map<String, Object>) resultFaceid.get("thresholds");

					// 比对率达到十万分之一的才被认为人脸认证通过
					if (Float.valueOf(resultFaceid.get("confidence") + "") >= Float.valueOf(thresholds.get("1e-4") + "")) {
						resultCode.setCode("0");
						resultCode.setMsg("成功");
					}
					HashMap<String, String> resultMap=new HashMap<String,String>();
					resultMap.put("confidence", resultFaceid.get("confidence").toString());
					resultMap.put("le3", thresholds.get("1e-3").toString());
					resultMap.put("le4", thresholds.get("1e-4").toString());
					resultMap.put("le5", thresholds.get("1e-5").toString());
					resultMap.put("le6", thresholds.get("1e-6").toString());
					resultMap.put("userId", map.get("userId"));
					resultCode.setParamsMap(resultMap);
					svaeFace(resultMap);
				}

			}
		}else{
			logger.info("人脸识别的时候需要传入userid编号已便保存人脸识别信息");
			resultCode.setMsg("请传入用户唯一标识编号");
		}
		return resultCode;
	}
	public JsonResult idcardScanning(Map<String, String> map) {
		JsonResult resultCode=new JsonResult("-1","失败");
		HashMap<String, String> params=new HashMap<String, String>();
		params.put("api_key",FaceConfig.FACE_API_KEY);
		params.put("api_secret",FaceConfig.FACE_API_SECRET);
		// 返回身份证照片合法性检查结果，值只取“0”或“1”。“1”：返回； “0”：不返回。默认“0”。
		params.put("legality","1");
		Map<String, String> fileMap = new HashMap<String, String>();
		/*图片地址*/
		fileMap.put("image",map.get("filePath"));
		String contentType = "";//image/png
//		System.out.println("请求参数"+params.toString());
		String ret = HttpUtil.formUploadImage(FaceConfig.FACE_API_BASE_URL + "/faceid/v1/ocridcard", params, fileMap,contentType);
		Map<String, Object> checkResult =new HashMap<String, Object>();
		try {
			checkResult=JSONUtil.parseJSON2Map(ret);
		}catch (Exception e){
			e.printStackTrace();
			resultCode.setMsg("识别失败,请重新尝试");
			return resultCode;
		}
		if(checkResult.containsKey("error")){
			resultCode.setMsg("识别失败,请重新尝试");
			return resultCode;
		}
		boolean isIdCardImageFront = "front".equals(checkResult.get("side"));
		// 保存附件信息至数据库
		// 保存一次身份证信息至数据库  但是不更新该用户的人脸识别状态
		// 判断该图片是否为身份证件正面 如果是正面那么将识别出的姓名和身份证号信息保存至
		HashMap<String, String> resultMap=new HashMap<String, String>();
		resultMap.put("isIdCardImageFront", isIdCardImageFront+"");
		if(isIdCardImageFront){
			String idCard = checkResult.get("id_card_number") + "";
			String userName = checkResult.get("name") + "";
			String gender=checkResult.get("gender")+"";
			resultMap.put("id_card_number", idCard);
			resultMap.put("name", userName);
			resultMap.put("gender",gender);
			resultCode.setCode("0");
			resultCode.setMsg("扫描成功");
		}
		resultCode.setParamsMap(resultMap);
		return resultCode;
	}
	/**
	 * 保存人脸识别信息
	 * @param parasmMap
	 */
	public void svaeFace(HashMap<String,String> parasmMap){
		if(parasmMap!=null){
			FaceRecognition face=faceFecogntionService.selectByUserId(Integer.parseInt(parasmMap.get("userId")));
			if(face==null){
				face=new FaceRecognition();
				face.setConfidence(parasmMap.get("confidence"));
				face.setUserId(Integer.parseInt(parasmMap.get("userId")));
				face.setLe3(parasmMap.get("le3"));
				face.setLe4(parasmMap.get("le4"));
				face.setLe5(parasmMap.get("le5"));
				face.setLe6(parasmMap.get("le6"));
				if (Float.valueOf(parasmMap.get("confidence") + "") >= Float.valueOf(parasmMap.get("le4") + "")) {
					face.setStatus("1");
				}else{
					face.setStatus("0");
				}
				faceFecogntionService.saveFaceRecognitionDao(face);
			}else{
				face.setConfidence(parasmMap.get("confidence"));
				face.setUserId(Integer.parseInt(parasmMap.get("userId")));
				face.setLe3(parasmMap.get("le3"));
				face.setLe4(parasmMap.get("le4"));
				face.setLe5(parasmMap.get("le5"));
				face.setLe6(parasmMap.get("le6"));
				if (Float.valueOf(parasmMap.get("confidence") + "") >= Float.valueOf(parasmMap.get("le4") + "")) {
					face.setStatus("1");
				}else{
					face.setStatus("0");
				}
				faceFecogntionService.updateFaceRecognition(face);
			}
		}
	}
}
